﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.Bedroomss
{
    public class DetailBedroomsHandler : IRequestHandler<DetailBedroomsCommand, Result<Bedrooms>>
    {
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> _bedroomRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DetailBedroomsHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="bedroomRepository"></param>
        /// <param name="logger"></param>
        public DetailBedroomsHandler(IBaseRepository<Bedrooms> bedroomRepository, ILogger<DetailBedroomsHandler> logger)
        {
            _bedroomRepository = bedroomRepository;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<Bedrooms>> Handle(DetailBedroomsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<Bedrooms>() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _bedroomRepository.GetAll()).Where(x => x.BedroomId == request.BedroomId).FirstOrDefaultAsync();
                if (query != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取栋舍成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取栋舍异常" + ex.Message;
                _logger.LogError("获取栋舍异常" + ex.Message);
            }
            return result;
        }
    }
}
